import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 store
import store from '@/store'

const Home = () => import('@/views/home/index.vue')
const Login = () => import('@/views/login/index.vue')
const Question = () => import('@/views/question/index.vue')
const Article = () => import('@/views/article/index.vue')
const User = () => import('@/views/user/index.vue')
const Video = () => import('@/views/video/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')
const Profile = () => import('@/views/user/profile/index.vue')
const Chat = () => import('@/views/chat/index.vue')
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    components: {
      default: Login
    }
  },
  {
    path: '/',
    alias: '/home',
    components: {
      default: Home,
      bottom: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    // path: '/article/:id',    //动态路由
    path: '/article/',
    components: {
      default: Article
    },
    name: 'routerArticle'
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    },
    meta: {
      // 设置路由元 true代表有token才能进的页面
      needLogin: true
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabbar
    }
  },
  {
    path: '/user/profile',
    components: {
      default: Profile
    }
  },
  {
    path: '/user/chat',
    components: {
      default: Chat
    }
  }
]

const router = new VueRouter({
  routes
})
// 白名单 没有token 不允许访问的页面 跳转到登录(/login)页面
// const whitePath = ['/user']

router.beforeEach((to, from, next) => {
  if (store.getters['login/getToken']) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // if (to.path.toLowerCase().startsWith('/user')) {
    // 白名单写法,要去的地址是否在白名单内 如果在白名单内 就直接去login页面
    // if (whitePath.includes(to.path.toLowerCase())) {
    // 路由元写法 判断路由元是否为true
    if (to.meta.needLogin) {
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}
export default router
